<template>
  <div class="ek-select-table">
    <el-tooltip placement="bottom" :visible="visible" effect="light">
      <div class="ek-select-table-box">
        <el-select
          popper-class="ek-select-table-popper"
          v-model="value"
          @clear="clear"
          loading-text="加载中"
          no-data-text="无数据"
          :placeholder="placeholder"
          :disabled="disabled"
          :clearable="clearable"
          :multiple="multiple"
          :collapse-tags="collapseTags"
          :collapse-tags-tooltip="collapseTagsTooltip"
          :size="size"
           @click.native="showPopover"
        >
          <el-option
            v-for="item in ekOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      
        <!-- <div class="ek-select-table-btn" @click.stop="showPopover"></div> -->
      </div>

      <template #content>
        <div class="ek-select-table-list">
          <ekList
            ref="refList"
            :layoutData="layoutData"
            size="small"
            style="height: 400px"
          />
          <div class="ek-select-table-footer">
            <el-button size="small" @click="cancel">取消</el-button>
            <el-button size="small" plain @click="confirm">确定</el-button>
          </div>
        </div>
      </template>
    </el-tooltip>
  </div>
</template>

<script setup>
import {
  defineComponent,
  defineEmits,
  onMounted,
  getCurrentInstance,
  computed,
  ref,
  watch,
  reactive,
  nextTick,
} from "vue";
import ekList from "@/components/business/ekList/index.vue";

const props = defineProps({
  modelValue: {
    type: [String, Number, Array, Boolean],
    default: "",
  },
  // 显示名称
  name: {
    type: [String, Array],
    default: "",
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否显示清除
  clearable: {
    type: Boolean,
    default: true,
  },
  // 默认显示
  placeholder: {
    type: String,
    default: "请选择",
  },
  // 获取对应模型映射数据接口
  url: {
    type: String,
    default: "",
  },
  // 是否多选
  multiple: {
    type: Boolean,
    default: false,
  },
  // 多选是否折叠
  collapseTags: {
    type: Boolean,
    default: true,
  },
  collapseTagsTooltip: {
    type: Boolean,
    default: true,
  },
  // 字段映射
  mapping: {
    type: Object,
    default: () => ({
      label: "label",
      value: "value",
    }),
  },
  size: {
    type: String,
    default: "default",
  },
  layoutData: {
    type: Object,
    default: () => {},
  },
});

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const {$http, $ekMessage } = globalProperties;

const emit = defineEmits(["update:modelValue", "change", "clear"]);

const value = computed({
  get() {
    if (props.multiple) {
      return props.modelValue;
    } else {
      return props.modelValue;
    }
  },
  set(value) {
    if (props.multiple) {
      emit("update:modelValue", value);
    } else {
      emit("update:modelValue", value);
    }
  },
});

// 选项列表
const ekOptions = ref([]);
const visible = ref(false);
const refList = ref(null);

function init() {
  if (
   (!props.multiple && (value.value || value.value === 0) && props.name) || ( props.multiple && value.value?.length && props.name?.length )
  ) {
    if (props.multiple) {
    
       for(let i = 0; i < value.value.length; i++){
          ekOptions.value.push({
            label: props.name[i],
            value: value.value[i],
          })
        }
    }else {
      ekOptions.value.push({
        label: props.name,
        value: value.value,
      });
    }
  }
}

function showPopover(){
  visible.value = true;
}
function cancel() {
  visible.value = false;
}
function confirm() {
  let rows = [];
  if (props.multiple) {
    rows = refList.value.getSelectionRows();
  } else {
    let row = refList.value.getCurrentRow();
    if (row) {
      rows = [refList.value.getCurrentRow()];
    }
  }

  if (rows.length) {
    nextTick(() => {
      if (props.multiple) {
        rows.forEach((element) => {
          ekOptions.value.push({
            label: element[props.mapping.label],
            value: element[props.mapping.value],
          });
        });
        let newRows = Array.from(
          new Set([
            ...rows.map((item) => item[props.mapping.value]),
            ...value.value,
          ])
        );
        ekOptions.value = uniqueByKey(ekOptions.value, "value");
        ekOptions.value = ekOptions.value.filter((item) =>
          newRows.includes(item.value)
        );
        value.value = newRows;
      } else {
        ekOptions.value = [];
        rows.forEach((element) => {
          ekOptions.value.push({
            label: element[props.mapping.label],
            value: element[props.mapping.value],
          });
        });
        value.value = rows.map((item) => item[props.mapping.value])[0];
      }
    });
  } else {
    nextTick(() => {
      if (props.multiple) {
        value.value = [];
      } else {
        value.value = "";
      }
    });
  }
  visible.value = false;
}

// 改变事件, 清空会返回undefined
function change(event) {
  emit("change", event);
}
// 清除事件
function clear() {
  emit("clear");
}
function uniqueByKey(arr, key) {
  const seen = new Set();
  return arr.filter((item, index) => {
    const keyValue = item[key];
    return seen.has(keyValue) ? false : seen.add(keyValue);
  });
}
onMounted(() => {
  init();
});
// todo 如果初始化不请求数据如何回显问题
</script>

<style lang="scss">
.ek-select-table-popper {
  display: none !important;
}
</style>
<style lang="scss" scoped>
.ek-select-table-box {
  position: relative;
  .ek-select-table-btn {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 32px;
    cursor: pointer;
    opacity: 0;
  }
}
.ek-select-table-list {
  width: 600px;
}
.ek-select-table-footer {
  padding-top: 8px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #eee;
}
</style>
